/*
 * [程序名称] Weather auto sender
 * [参考资料] http://code.google.com/p/auto-weather-sender/ 
 * [开源协议] Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.joe.weather.tool;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class WeatherUtil
{
	private static final String TAG = WeatherUtil.class.getSimpleName();
	
	// http://m.weather.com.cn/data/101280101.html
	private static final String URL_WEATHER_API = "http://m.weather.com.cn/data/%s.html";
	
	public static String getSMSMessage(String callName, String cityCode, String cityName)
	{
		StringBuilder sb = new StringBuilder("");
		JSONObject weatherObject = getJsonData(cityCode);
		if(weatherObject != null)
		{
			try
			{
				sb.append(callName);
				sb.append("，今天是");
				sb.append(weatherObject.getString("date_y"));
				sb.append("，");
				sb.append(weatherObject.getString("week"));
				sb.append("，温度：");
				sb.append(weatherObject.getString("temp1"));
				sb.append("。\n明天温度：");
				sb.append(weatherObject.getString("temp2"));
				sb.append("，天气：");
				sb.append(weatherObject.getString("weather2"));
				sb.append("，");
				sb.append(weatherObject.getString("wind2"));
				sb.append("。\n（");
				sb.append(cityName);
				sb.append("）");
			}
			catch (JSONException e)
			{
				e.printStackTrace();
			}
		}
		
		return sb.toString();
	}
	
	private static JSONObject getJsonData(String cityCode)
	{
		String url = String.format(URL_WEATHER_API, cityCode);
		JSONObject jsonObject = null;
		DefaultHttpClient httpClient = null;
		HttpParams httpParameters = null;
		final int timeoutConnection = 5000;  
		final int timeoutSocket = 8000;  
		
		try
		{
			httpParameters = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
			HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); 
			httpClient = new DefaultHttpClient(httpParameters); 
			
			HttpGet httpGet = new HttpGet(url);
			Log.e(TAG, "executing request: " + httpGet.getURI());
			
			HttpResponse response = httpClient.execute(httpGet);
			// Get hold of the response entity
            HttpEntity entity = response.getEntity();
            String result = "";

            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
            {
            	if (entity != null) 
            	{
            		InputStream inStream = entity.getContent();
            		try
            		{
            			BufferedReader reader = new BufferedReader(
            				 new InputStreamReader(inStream, HTTP.UTF_8), 8);
            			StringBuilder sb = new StringBuilder();
            			String line = null;
            			while ((line = reader.readLine()) != null) 
            			{
            				sb.append(line + "\n");
            			}
            			inStream.close();
            			result = sb.toString();
            			
            			Log.e("WeatherUtil", "Weather Info get from google is:::" + result);
            			JSONObject object = new JSONObject(result);
            			jsonObject = object.getJSONObject("weatherinfo");
            			Log.e("WeatherUtil", "jsonObject is null :::" + (jsonObject==null));
            		}
            		catch (IOException ex) 
            		{
            			Log.e(TAG, ex.toString());
                        throw ex;
                    } 
            		catch (RuntimeException ex) 
            		{
                        httpGet.abort();
                        Log.e(TAG, ex.toString());
                        throw ex;
                    } 
            	}
            }
            else
            {
            	Log.e(TAG, "Http Get Error.........");
            }
		}
		catch (MalformedURLException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		catch (JSONException e)
		{
			e.printStackTrace();
		}
		finally
		{
			httpClient.getConnectionManager().shutdown();
		}
		
		return jsonObject;
	}
}
